/**
 * Created by hucy on 2016-05-19.
 */
admin.controller('DeptListCtrl',[
	'$scope',
  '$location',
	'$http',
  '$uibModal',
  'load2scope',
  'removeFromList',
  function($scope,$location,$http,$uibModal,load2scope ,removeFromList){
    load2scope( ['dept'] , $scope );
  	$scope.showDetail = function () {
  		var id = $('[name="ids"]:checked').val();
      if(!id) return;
  		$location.path('/detail/dept/'+id);
  	};
    // 删除部门
    $scope.remove = function () {
      var option = {
        $scope : $scope,
        table  : 'dept',
        modalConfig : {
          title:'删除确认',
          content:'您确定要删除该项？<br />\
                  <strong>此操作不可逆！</strong>',
        }
      };
      removeFromList(option);
    }
	}
])
.controller('DeptDetailCtrl',[
	'$scope',
	'$uibModal',
  '$http',
	'$stateParams',
	'localStorageService',
	'util',
  function($scope,$uibModal,$http,$stateParams,localStorageService,util){
  	var id = $stateParams.id;

  	$scope.map = {};

  	$scope.dept = localStorageService.get('dept');
  	$scope.map.dept = util.array2map( $scope.dept );
    $scope.deptItem = $scope.map.dept[id];

    $scope.update  = true;
    $scope.tempDept = {};
  	// 切换修改状态
  	$scope.toggleUpdate = function () {

  		if( $scope.update ){
  			// 暂存
  			$.extend($scope.tempDept,$scope.deptItem);
        console.log('暂存');
      }else{
        $.extend($scope.deptItem,$scope.tempDept);
        console.log('取消');
      }
      $scope.update = !$scope.update;
    }
    // 修改部门信息
    $scope.modify = function () {
      $http.put('/api/dept/'+$scope.deptItem.id , $scope.deptItem).then(function (data) {
        // console.log(data);
        show_stack('success2');
        $scope.toggleUpdate();

      }, function () {
        console.log('fail');
      });
    }
	}
])

.controller('DeptAddCtrl', [
  '$scope',
  'localStorageService',
  '$http',
  '$location',
  function($scope,localStorageService,$http,$location){
    $scope.deptItem = {};
    var deptList = localStorageService.get('dept');
    var len = deptList.length;
    var id  = parseInt(deptList[len-1].id) + 1;
    $scope.deptItem.id = id;
    $scope.deptItem.dept_desc = '部门简介'
    $scope.add = function () {
      console.log($scope.deptItem)
      $http.post('/api/dept', $scope.deptItem)
        .success(function (data) {
          show_stack('success-add');
          deptList.push($scope.deptItem);
          localStorageService.set('dept' , deptList);
          $location.path('/detail/dept/'+id);
        })
    }
    $scope.back = function () {
      $location.path('/list/dept');
    }
  }
])

